package com.curluin.inputInterpretation;

import com.curluin.controll.Controller;
import com.curluin.math.MyVector;

import android.view.MotionEvent;

public class TouchInterpreter {
	
	public static final String LOG_TAG = "TouchInterpreter";
	
	/**
	 * Controller
	 */
	Controller controller = null;
	
	/**
	 * Current TouchEvent
	 */
	TouchEvent curTouchEvent;
	
	/**
	 * Screensize, first element width, second element height
	 */
	MyVector screenSize;
	
	/**
	 * Constructor
	 * @param controller
	 */
	public TouchInterpreter(Controller controller, int screenWidth, int screenHeight){
		this.controller = controller;
		this.screenSize = MyVector.makeVector2(screenWidth, screenHeight);
		curTouchEvent = new TouchEvent();
	}
	
	/**
	 * Handles MotionEvent and converts it into a TouchEvent by extracting relevant information
	 * @param event
	 */
	public void handleEvent(MotionEvent event){
		TouchPoint touchPoint = new TouchPoint(event, screenSize);		
		
		// Touch started
		if (event.getAction() == MotionEvent.ACTION_DOWN){
			curTouchEvent.clear();
			curTouchEvent.setDownPoint(touchPoint);
			curTouchEvent.state = TouchEvent.TOUCH_STARTED;
		// Touch ongoing
		}else if (event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_UP) {
			if (curTouchEvent.trajectory.size() > 1){
				touchPoint.computeInstantaneousVelocity(curTouchEvent.getLastTouchPoint());
				touchPoint.computeOffset(curTouchEvent.getLastTouchPoint());
			}
			// Wiping
			if (event.getAction() == MotionEvent.ACTION_MOVE){
				curTouchEvent.trajectory.add(touchPoint);
				curTouchEvent.state = TouchEvent.TOUCH_MOVING;
			}
			// Touch finished
			if (event.getAction() == MotionEvent.ACTION_UP){
				curTouchEvent.setUpPoint(touchPoint);
				curTouchEvent.state = TouchEvent.TOUCH_FINISHED;
//				lastSide = side;
			}
		}else return;
		
		// Forward TouchEvent to Controller		
		controller.handleTouchEvent(curTouchEvent);
	}

	public void destroy() {
		curTouchEvent.clear();
		curTouchEvent = null;
		screenSize = null;
		controller = null;
	}

}
